<?php
/**
 * 前台项目基类
 * 
 + ----------------------------------------------------- 
 * Date 2013-3-8
 + -----------------------------------------------------
 */
class BaseAction extends Action {

    function _initialize() {
    	
		$this->assign('suffix',C('TMPL_TEMPLATE_SUFFIX'));
		
		//获取配置参数
		$this->_config();
		//当前栏目
		$this->assign('current_menu',$this->getCurrentMenu());
		//网站标题
		$this->assign('title',$this->_getTitle());
		// 获取导航列表
		$this->assign('navigation',$this->_getNavigation());
		// 广告
		$this->assign('slide',$this->getAd(1,10));
		// banner
		$this->assign('banner',$this->getAd(2,1));
		
		//$this->assign('friend_link',$this->_getFriendLink());
		
		if($_REQUEST['mid']){
			$mid = $_REQUEST['mid'];
		}elseif($_REQUEST['id']){
			$model = M("Article");
			$mid = $model->where("id=".$_REQUEST['id'])->getField("menu_id");
		}
		$topid=$this->getTopid($mid);
		$this->assign('topid',$topid);
		$model = M("Menu");
		$this->assign('topmenu',$model->find($topid));
    	// 子页面左侧
    	$model=D("Menu");
    	$sub_menu = $model->getSubmenuList($topid,100);
    	$this->assign('sub_menu',$sub_menu);
    }
    
    /**
     * 获取网站配置
     * @return array
     */
    protected function _config(){
    	$config = M("Config");
    	$list = $config->getField('name,value');
    	if(!empty($list)&&is_array($list)){
    		foreach($list as $k=>$v){
    			C(strtoupper($k),$v);
    		}
    	}
    	// 客服处理
    	$this->assign('kf1',$this->parseKf(C('SITE_KF')));
    	$this->assign('kf2',$this->parseKf(C('SITE_KF_HEZUO')));
    	$this->assign('kf3',$this->parseKf(C('SITE_KF_QUN')));
    }
    
    /**
     * 取顶级ID
     * @param unknown_type $mid
     */
    public function getTopid($mid){
    	$model=M('Menu');
    	$menu=$model->find($mid);
    	if($menu['parent_id']){
    		return $menu['parent_id'];
    	}else{
    		return $mid;
    	}
    }
    
    /**
     * 解析客服
     * +------------------------------------------------------
     * Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
     * Date 2013-3-26
     * +------------------------------------------------------
     * @param string $str
     */
    public function parseKf($str){
    	$kf=@explode('|', $str);
    	$arr=array();
    	if(is_array($kf) && count($kf)>0){
    		foreach ($kf as $k=>$v){
    			$array=@explode(',', $v);
    			$arr[]=array('name'=>$array[1],'value'=>$array[0]);
    		}
    	}
    	return $arr;
    }
    
    /**
     * 左侧
     */
    public function getLeftMenu($pid=0,$pos_id=0,$mid=array()){
    	$menu=M('Menu');
    	$map=array();
    	if(is_array($pid)){
    		$map['m.parent_id']=array('in',$pid);
    	}else{
    		$map['m.parent_id']=$pid;
    	}
    	if(is_array($mid) && count($mid)>0){
    		$map['m.id']=$mid;
    	}
    	if($pos_id){
    		$map['m.pos_id']=$pos_id;
    	}
    	$menus=$menu->table(C("DB_PREFIX")."menu m")
	    	->join("left join ".C("DB_PREFIX")."menu_type t on m.type_id=t.id")
	    	->field("m.*,t.name,t.model")
	    	->where($map)
	    	->order("m.sort_order asc")
	    	->select();
    	$array=array();
    	//dump($menus);exit;
    	if(is_array($menus)&&count($menus)>0){
    		foreach($menus as $k=>$v){
    			$array[$k]=$v;
    			$submenus=$this->getLeftMenu($v['id']);
    			if(empty($submenus)){
    				$array[$k]['submenus']=array($v);
    			}else{
    				//$array[$k]['submenus']=array_merge($submenus,array($v));
    				$array[$k]['submenus']=$submenus;
    				$array[$k]['count']	=	count($submenus)-1;
    			}
    		}
    	}
    	//dump($array);exit;
    	return $array;
    }
    
    /**
     * 取当前栏目
     */
    public function getCurrentMenu(){
    	$model=M('Menu');
    	if(isset($_GET['mid'])&&intval($_GET['mid'])){
    		$current_menu=$model->find($_GET['mid']);
    		C('SITE_KEYWORDS',$current_menu['menu_keyword']);
    		C('SITE_DESCRIPTION',$current_menu['menu_description']);
    		return $current_menu;
    	}else{
    		return array();
    	}
    }
    
    /**
     * 查找某个模块的标签相关的记录ID
     */
    public function getRecordIds($tag, $model = MODULE_NAME) {
    	$Tag=M('Tag');
    	$recordIds='';
    	$tagId = $Tag->where("model='".$model."' and name='".$tag."'")->getField('id');
    	if($tagId){
	    	$Tagged = M("Tagged");
	    	$recordIds = $Tagged->where("model='" . $model . "' and tag_id=" . $tagId)->getField('id,record_id');
    	}
    	return $recordIds;
    }
    
    /**
     * 获取广告
     * @param unknown_type $pos_id
     * @param unknown_type $num
     */
    public function getAd($pos_id,$num=5,$order="a.sort_order asc"){
    	$model=M("Ad");
    	$map=array(
    		'a.position_id'	=>	$pos_id,		
    	);
    	$ads=$model->table(C('DB_PREFIX').'ad as a')
    			->join('left join '.C('DB_PREFIX').'ad_position as p on(a.position_id=p.id)')
    			->field('a.*,p.width,p.height')
    			->where($map)->limit($num)->order($order)->select();
    	return $ads;
    }
    
    /**
     * 获取文章
     * @param int $num
     * @param string $order
     * @param bool $is_recom
     */
    public function getArticle($num,$mid=0,$order='',$is_rec=false,$is_top=false,$is_pic=false,$tag=0){
    	$model=M('Article');
    	if(empty($order)){
    		$pk=$model->getPk();
    		$order='a.'.$pk.' desc';
    	}elseif($order=='rand()'){
			$order='rand()';
		}else{
    		$order='a.'.$order;
    	}
    	$map['a.status']=1;
    	if(is_array($mid)){
    		$map['a.menu_id']=array("in",$mid);
    	}elseif($mid){
    		// 所有子分类ID
    		$Menu = D('Menu');
    		$child = $Menu->getSubmenuId($mid);
    		$map['a.menu_id']=array('in',$child);
    	}
    	if($is_rec){
    		$map['a.is_rec']=1;
    	}
    	if($is_top){
    		$map['a.is_top']=1;
    	}
    	if($is_pic){
    		$map['a.image']=array('neq','');
    	}
		if($tag==1){
    		$map['a.type_id']=1;
    	}elseif($tag==2){
    		$map['a.type_id']=2;
    	}
    	$arts   =  $model->table(C("DB_PREFIX").'article a')
    				->join('left join '.C("DB_PREFIX").'menu m on(a.menu_id=m.id)')
			    	->field('a.*,m.menu_name')
			    	->where($map)
			    	->order($order)
			    	->limit($num)
			    	->select();
    	return $arts;
    }
    
    /**
     * 获取导航菜单
     * @return array
     */
    protected function _getNavigation($num=0) {
    	
    	$Menu   =  D('Menu');
    	$navs   =  $Menu->table(C('DB_PREFIX').'menu m')
			    		->join('left join '.C('DB_PREFIX').'menu_type t on(m.type_id=t.id)')
			    		->field('m.id,m.menu_name,m.menu_url,m.link_id,t.model')
			    		->where('m.parent_id=0 and m.status=1')
			    		->order('m.sort_order asc,m.id asc')
			    		//->limit(6)
			    		->select();
    	$new=array();
    	if(is_array($navs)&&count($navs)>0){
    		foreach($navs as $k=>$v){
    			$new[$k]=$v;
    			$new[$k]['subids']=$Menu->getSubmenuId($v['id']);
    			$subs   =  $Menu->table(C('DB_PREFIX').'menu m')
		    			->join('left join '.C('DB_PREFIX').'menu_type t on(m.type_id=t.id)')
		    			->field('m.id,m.menu_name,m.menu_url,m.link_id,t.model')
		    			->where('m.parent_id='.$v['id'].' and m.status=1')
		    			->order('m.sort_order asc,m.id asc')
		    			->select();
    			$new[$k]['child']=$subs;
    		}
    	}
        return $new;
    }
	
    /**
     * 获取友情链接
     * @param int $num 条数
     * @return array
     */
    protected function _getFriendLink($num=0,$is_first=0){
    	$model=M('FriendLink');
    	$map=array(
    		'status'	=>	1		
    	);
    	if($num){
    		$links=$model->where($map)->order('sort_order asc')->limit($num)->select();
    	}else{
    		$links=$model->where($map)->order('sort_order asc')->select();
    	}
    	return $links;
    }
    
    /**
     * 获取标签云
     * @param int $num 条数
     * @return array
     */
    protected function _getTags($num=0,$order='rand()'){
    	$model=M('Tag');
    	if($num){
    		$tags=$model->order($order)->limit($num)->select();
    	}else{
    		$tags=$model->order($order)->select();
    	}
    	return $tags;
    }
    
	 /**
     * 获取站点当前位置
	 * @return string
     */
    protected function _getPosition(){
    	$menu_id=isset($_REQUEST['mid']) ? intval($_REQUEST['mid']) : 0;
		$id=isset($_REQUEST['id']) ? intval($_REQUEST['id']) : 0;
		if($id){
			$model=M("Article");
			$art=$model->find($id);
			$menu_id=$art['menu_id'];
		}
    	$pos='';
		$array=array();
    	if($menu_id){
    		$Menu=M('Menu');
    		$path=$Menu->where('id='.$menu_id)->getField('path').'-'.$menu_id;
    		if(strpos($path,'-')){
    			$ids=explode('-',$path);
    			//arsort($ids,SORT_NUMERIC);
    			$array=array();
    			if(is_array($ids)&&count($ids)>0){
    				$map=array(
						'id'	=>	array('in',$ids)
					);
    				$array=$Menu->where($map)->getField('id,link_id,menu_name');
    			}
    		}
    	}
    	return array(
			'pos_menu'=>$array
		);
    }
	
    /**
     * 获取站点动态标题
	 * @return string
     */
    protected function _getTitle(){
    	$mid=isset($_REQUEST['mid']) ? intval($_REQUEST['mid']) : 0;
    	$title='';
		$array=array();
    	if($mid){
    		$Menu=M('Menu');
    		$menu_name=$Menu->where('id='.$mid)->getField('menu_name');
    		if($menu_name){

    			$array[]=$menu_name.' - '.C('SITE_TITLE');
    		}else{
    			$array[]=C('SITE_TITLE');
    		}
    	}else{
    		$array[]=C('SITE_TITLE');
    	}
		if(count($array)>0){
			$title=implode('-',$array);
		}
    	return $title;
    }
    
    /**
      +----------------------------------------------------------
     * 根据表单生成查询条件
     * 进行列表过滤
      +----------------------------------------------------------
     * @access protected
      +----------------------------------------------------------
     * @param Model $model 数据对象
     * @param HashMap $map 过滤条件
     * @param string $sortBy 排序
     * @param boolean $asc 是否正序
      +----------------------------------------------------------
     * @return void
      +----------------------------------------------------------
     * @throws ThinkExecption
      +----------------------------------------------------------
     */
    protected function _list($model = '', $map = '', $page_size=15, $sortBy = '', $asc = false) {
        $model = empty($model) ? M($this->getActionName()) : $model;
        if (isset($_REQUEST['_order'])) {
            $order = 'a.'.$_REQUEST['_order'];
        } else {
            $order = !empty($sortBy) ? 'a.'.$sortBy : 'a.'.$model->getPk();
        }
        if (isset($_REQUEST['_sort'])) {
            $sort = $_REQUEST['_sort'] ? 'asc' : 'desc';
        } else {
            $sort = $asc ? 'asc' : 'desc';
        }
        $map['a.status']	=	1;
        //记录数
        $count = $model->table(C("DB_PREFIX").'article a')
        			->join('left join '.C('DB_PREFIX').'menu m on(a.menu_id=m.id)')
			    	->field('a.id,m.menu_name')
			    	->where($map)
					->count('a.id');
        //echo $model->getLastSql();exit;
        if ($count > 0) {
            //分页显示
            import("ORG.Util.Page");
            $p = new Page($count, $page_size);
			//$p->rollPage=10;
            $page = $p->show();
			$list=$model->table(C("DB_PREFIX").'article a')
					->join('left join '.C('DB_PREFIX').'menu m on(a.menu_id=m.id)')
			    	->field('a.*,m.menu_name')
			    	->where($map)
			    	->order($order . ' ' . $sort)
			    	->limit($p->firstRow. ','.$p->listRows)
			    	->select();
			//echo $model->getLastSql();exit;
            $this->assign('page', $page);
			$new_list=array();
			foreach($list as $k=>$v){
				$new_list[$k]=$v;
				$tag=empty($_REQUEST['tag']) ? '' : urldecode($_REQUEST['tag']);
				$kw=empty($_REQUEST['k']) ? '' : urldecode($_REQUEST['k']);
				if($tag){
					$new_list[$k]['title']=preg_replace('/'.$tag.'/','<font color=red>'.$tag.'</font>',$v['title']);
				}elseif($kw){
					$new_list[$k]['title']=preg_replace('/'.$kw.'/','<font color=red>'.$kw.'</font>',$v['title']);
				}
				$new_list[$k]['tags']=empty($v['tags']) ? array() : @explode(' ',$v['tags']);
			}
			//dump($new_list);exit;
            $this->assign('list', $new_list);
        }
		return;
    }
	
    /**
     * Ajax评论 
     * 实现不同模块的评论
     */
    public function ajaxComment(){
    	$record_id=isset($_POST['record_id']) ? intval($_POST['record_id']) : 0;
    	//$name=isset($_POST['name']) ? trim($_POST['name']) : '';
    	//$email=isset($_POST['email']) ? trim($_POST['email']) : '';
    	$content=isset($_POST['content']) ? trim($_POST['content']) : '';
    	//$code=isset($_POST['code']) ? intval($_POST['code']) : '';
    	if(md5($code) != $_SESSION['code']){
    		//$this->ajaxReturn(0,'发表评论失败，验证码错误！',0);
    	}
    	if(!$_SESSION['UserInfo']['user_id']){
    		$this->ajaxReturn(0,'对不起，登录才能发表！',0);
    	}
    	if($record_id && $content){
    		$data=array(
    				'record_id'	=>	$record_id,
    				'user_id'	=>	$_SESSION['UserInfo']['user_id'],
    				'name'		=>	$_SESSION['UserInfo']['username'],
    				//'email'		=>	$email,
    				'content'	=>	$content,
    				'ip'		=>	get_real_ip(),
    				'model'		=>	MODULE_NAME,
    				'add_time'	=>	time()
    		);
    		$model=M("Comment");
    		if(false !== $comment_id=$model->add($data)){
    			$info=$model->getById($comment_id);
    			$info['add_time']=date('Y-m-d H:i',$info['add_time']);
    			$this->ajaxReturn($info,'恭喜您，发表成功！',1);
    		}else{
    			$this->ajaxReturn(0,'对不起，发表失败！',0);
    		}
    	}else{
    		$this->ajaxReturn(0,'对不起，发表失败！',0);
    	}
    }
    
    /**
     * 发表心情
     */
    public function clickMood(){
    	$id=isset($_REQUEST['id']) ? intval($_REQUEST['id']) : 0;
    	$value=isset($_REQUEST['value']) ? intval($_REQUEST['value']) : 0;
    	$model=M("Article");
    	$info=$model->find($id);
    	$count=$info['mood'.$value]+1;
    	$map=array(
    		'id'	=>	$id		
    	);
    	$data=array(
    		'mood'.$value	=>	$count,
    		'mood_time'		=>	time(),
    		'mood_ip'		=>	get_real_ip()
    	);
    	if($info['mood_time']-time() <= 3600 && $info['mood_ip']==get_real_ip()){
    		$this->ajaxReturn(0,'发表心情失败，同IP1小时内不能重复发表！',0);
    	}
    	if($value && $id){
    		if($model->where($map)->save($data)){
    			$res=array(
    				'value'	=>	$value,
    				'count'	=>	$count		
    			);
    			$this->ajaxReturn($res,'发表心情成功！',1);
    		}else{
    			$this->ajaxReturn(0,'发表心情失败！',0);
    		}
    		
    	}else{
    		$this->ajaxReturn(0,'发表心情失败！',0);
    	}
    }
    
    /**
     * 获取记录评论
     */
    public function getRecordComment(){
    	$id=isset($_REQUEST['id']) ? intval($_REQUEST['id']) : 0;
    	$model_name=$this->getActionName();
    	$map=array(
    		'record_id'	=>	$id,
    		'model'		=>	$model_name,
    	);
    	$model=M('Comment');
    	$comments=$model->where($map)->order('add_time asc')->select();
    	$this->ajaxReturn($comments,'拉取评论成功！',1);
    }
    
    
    /**
     * 非法操作提示
     * @param string $method
     */
    public function _empty($method) {
    	
        $this->error('非法操作！');
        
    }
    
    /**
     * 404 错误重定向
     * @param string $message
     * @param string $jumpUrl
     * @param int $waitSecond
     */
    protected function _404($message = '', $jumpUrl = '', $waitSecond = 3) {
    	$this->assign('message', empty($message) ? '您访问的页面不存在，整努力为您跳转！' : $message);
    	if (!empty($jumpUrl)) {
    		$this->assign('jumpUrl', $jumpUrl);
    		$this->assign('waitSecond', $waitSecond);
    	}
    	$this->display(C('TMPL_ACTION_ERROR'));
    }
    
    /**
     * 验证码
     */
    public function verify() {
    	import("ORG.Util.Image");
    	Image::buildImageVerify(4,1,'gif',100,26,'code');
    }
	
}

?>